package com.mg.axechen.webview;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ProgressBar;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.tencent.smtt.export.external.interfaces.SslError;
import com.tencent.smtt.export.external.interfaces.SslErrorHandler;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;

/**
 * 带进度掉的WebView
 *
 * @author AxeChen
 */
public class BaseWebView extends FrameLayout {

    private final String TAG = "BaseWebView";

    /**
     * 网页最大进度
     */
    private final int MAX_PROGRESS = 100;

    /**
     * 布局加载器
     */
    private LayoutInflater mInflater;

    /**
     * webView
     */
    private WebView mWebView;

    /**
     * webView 容器
     */
    private FrameLayout mWebViewContainer;

    /**
     * 顶层View
     */
    private View mBaseView;

    /**
     * 网页进度条
     */
    private ProgressBar mProgressBar;


    public BaseWebView(@NonNull Context context) {
        this(context, null);
    }

    public BaseWebView(@NonNull Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public BaseWebView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView(context);
    }

    /**
     * 加载Url，标题从网页中获取
     *
     * @param url
     */
    public void loadUrl(String url) {
        if (mWebView == null) {
            return;
        }
        mWebView.loadUrl(url);
    }


    private void initView(Context context) {
        mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        mBaseView = mInflater.inflate(R.layout.layout_base_webview, this);
    }


    /**
     * 初始化控件
     *
     * @param config
     */
    public void init(BaseWebViewConfig config) {
        initWebView();
        initProgressBar();
        initWebSettings(config);
        initWebClient();
    }

    /**
     * 初始化WebView
     */
    private void initWebView() {
        mWebViewContainer = findViewById(R.id.flWebViewContainer);
        mWebView = new WebView(getContext());
        mWebViewContainer.addView(mWebView, new LayoutParams(
                LayoutParams.MATCH_PARENT,
                LayoutParams.MATCH_PARENT
        ));

    }

    /**
     * 初始化ProgressBar
     */
    private void initProgressBar() {
        mProgressBar = mBaseView.findViewById(R.id.webViewProgress);
    }

    /**
     * 初始化WebSetting
     */
    private void initWebSettings(BaseWebViewConfig config) {
        if (mWebView == null) {
            Log.i(TAG,"webView is null!");
            return;
        }

        if(config == null){
            config = new BaseWebViewConfig.Builder().build();
        }

        WebSettings webSetting = mWebView.getSettings();
        webSetting.setAllowContentAccess(config.allowContentAccess);
        webSetting.setAllowFileAccess(config.allowFileAccess);
        webSetting.setAllowFileAccessFromFileURLs(config.allowFileAccessFromFileURLs);
        webSetting.setAllowUniversalAccessFromFileURLs(config.allowUniversalAccessFromFileURLs);
        webSetting.setAppCacheEnabled(config.appCacheEnabled);
        webSetting.setAppCachePath(config.appCachePath);
        webSetting.setBlockNetworkImage(config.blockNetworkImage);
        webSetting.setBuiltInZoomControls(config.builtInZoomControls);
        webSetting.setCacheMode(config.cacheMode);
        webSetting.setCursiveFontFamily(config.cursiveFontFamily);
        webSetting.setDatabaseEnabled(config.databaseEnabled);
        webSetting.setDefaultFixedFontSize(config.defaultFixedFontSize);
        webSetting.setDefaultFontSize(config.defaultFontSize);
        webSetting.setDefaultTextEncodingName(config.defaultTextEncodingName);
        webSetting.setDisplayZoomControls(config.displayZoomControls);
        webSetting.setDomStorageEnabled(config.domStorageEnabled);
        webSetting.setFantasyFontFamily(config.fantasyFontFamily);
        webSetting.setFixedFontFamily(config.fixedFontFamily);
        webSetting.setGeolocationEnabled(config.geolocationEnabled);
        webSetting.setGeolocationDatabasePath(config.geolocationDatabasePath);
        webSetting.setJavaScriptCanOpenWindowsAutomatically(config.javaScriptCanOpenWindowsAutomatically);
        webSetting.setJavaScriptEnabled(config.javaScriptEnabled);
        webSetting.setLayoutAlgorithm(config.layoutAlgorithm);
        webSetting.setLoadWithOverviewMode(config.loadWithOverviewMode);
        webSetting.setLoadsImagesAutomatically(config.loadsImagesAutomatically);
        webSetting.setMediaPlaybackRequiresUserGesture(config.mediaPlaybackRequiresUserGesture);
        webSetting.setMinimumFontSize(config.minimumFontSize);
        webSetting.setMinimumLogicalFontSize(config.minimumLogicalFontSize);
        webSetting.setMixedContentMode(config.mixedContentMode);
        webSetting.setNeedInitialFocus(config.needInitialFocus);
        webSetting.setSansSerifFontFamily(config.sansSerifFontFamily);
        webSetting.setSaveFormData(config.saveFormData);
        webSetting.setSerifFontFamily(config.serifFontFamily);
        webSetting.setStandardFontFamily(config.standardFontFamily);
        webSetting.setSupportMultipleWindows(config.supportMultipleWindows);
        webSetting.setSupportZoom(config.supportZoom);
        webSetting.setTextZoom(config.textZoom);
        webSetting.setUseWideViewPort(config.useWideViewPort);
        webSetting.setUserAgentString(config.userAgentString);
    }

    /**
     * webView回退处理
     *
     * @return true可以回退 false不可以再回退
     */
    public boolean doBack(){
        if(mWebView.canGoBack()){
           mWebView.goBack();
           return true;
        }
        return false;
    }

    /**
     * webview前进页面
     *
     * @return true能够前进页面
     */
    public boolean forward(){
        if(mWebView.canGoForward()){
            mWebView.goForward();
            return true;
        }
        return false;
    }

    private void initWebClient() {
        if (mWebView == null) {
            return;
        }

        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView webView, String s) {
                super.onPageFinished(webView, s);
            }

            @Override
            public void onReceivedSslError(WebView webView, SslErrorHandler sslErrorHandler, SslError sslError) {
                super.onReceivedSslError(webView, sslErrorHandler, sslError);
            }


        });

        mWebView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView webView, int i) {
                super.onProgressChanged(webView, i);
                // 设置ProgressBar的进度
                mProgressBar.setProgress(i);

                // 网页加载完成时，隐藏ProgressBar
                if (i == MAX_PROGRESS) {
                    new Handler(Looper.myLooper()).postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            mProgressBar.setVisibility(View.GONE);
                        }
                    }, 200);
                } else {
                    mProgressBar.setVisibility(View.VISIBLE);
                }

            }
        });
    }


    /**
     * 获取当前WebView，去自定义实现功能
     *
     * @return
     */
    public WebView getWebView() {
        return mWebView;
    }

    /**
     * 简单的网页回调，如需要自定义更多功能，请获取WebView实现{@link #getWebView()}
     */
    public interface SimpleWebViewEvent {

        /**
         * 回调从网页中获取到的标题
         *
         * @param title
         */
        void onTitleChange(String title);

        /**
         * 下载回调
         *
         * @param url
         */
        void onDownLoad(String url);

    }
}
